package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.annotations.Ignore;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description RoleServiceImpl
 * @Author apeng
 * @Date 2024-10-24
 */
//构造器注入
@RequiredArgsConstructor
@Service
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;

    @Override
    public ResponseResult<PageResponse<RoleVo>> findRoleVoPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
       Page<RoleVo> page = roleMapper.selectPage(roleDto);
        PageResponse<RoleVo> roleVoPageResponse = PageResponse.of(page, RoleVo.class);
        return ResponseResult.success(roleVoPageResponse);
    }

    //添加角色
    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insertSelective(role);
    }

    private final RoleResourceMapper roleResourceMapper;

    //根据角色查询选中的资源数据
    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleResourceMapper.findCheckedResources(roleId);
    }

    //角色修改
    @Override
    public ResponseResult<Boolean> updateRole(RoleDto roleDto) {
        //1.将roleDto转换为role对象
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //2.调用mapper直接修改角色单表数据(解决编辑角色，启用或禁用)
        //2.1 判断是否操作为禁用
        if (SuperConstant.DATA_STATE_1.equals(roleDto.getDataState())) {
        //2.2.1 获取角色分配用户的数量
            Integer count = roleResourceMapper.findCountByRoleId(roleDto.getId());
            if (count > 0){
                throw new RuntimeException("角色关联用户不可以禁用");
                //2.2.2 数量大于0，抛出异常，该角色关联用户不可以禁用
            }
        }
        //2.2 直接修改
        roleMapper.updateByPrimaryKeySelective(role);
        //3.判断用户是否传递了分配资源编号集合数据（如果有关联的资源编号说明前端是点击菜单权限分配保存按钮）
        if (roleDto.getCheckedResourceNos() != null && roleDto.getCheckedResourceNos().length>0){
            //3.1 不为null并且数组长度大于0，先删除角色关联的资源中间表数据
            roleResourceMapper.deleteByRoleId(role.getId());
            //3.2 封装构建中间表集合数据List<RoleResource>
            List<RoleResource> roleResources = Arrays.stream(roleDto.getCheckedResourceNos())
                    .map(i -> {
                        return RoleResource.builder()
                                .roleId(roleDto.getId())
                                .dataState(SuperConstant.DATA_STATE_0)
                                .resourceNo(i)
                                .build();
                    }).collect(Collectors.toList());
            //3.3 将中间表集合数据List<RoleResource>批量插入中间表中
            roleResourceMapper.batchInsert(roleResources);
        }else if (roleDto.getCheckedResourceNos() != null && roleDto.getCheckedResourceNos().length == 0){
            //4.  不为null并且数组长度等于0，抛出异常，提示用户请勾选分配的资源
            if (roleResourceMapper.findCountByRoleId(role.getId()) > 0){
                roleResourceMapper.deleteByRoleId(role.getId());
            }else {
                throw new RuntimeException("请勾选分配的资源");
            }
        }
        return ResponseResult.success(true);
    }

    private final UserRoleMapper userRoleMapper;

    /**
     * 删除角色
     */
    @Override
    public ResponseResult deleteRole(Long roleId) {
        //直接删除角色
        roleMapper.deleteByPrimaryKey(roleId);
        //删除角色资源表;
        roleResourceMapper.deleteByRoleId(roleId);
        //删除角色用户表
        userRoleMapper.deleteByPrimaryKey(roleId);
        return ResponseResult.success(true);
    }

    //角色下拉框
    @Override
    public ResponseResult initRoles() {
       List<RoleVo> list = roleMapper.initRoles();
        return ResponseResult.success(list);
    }
}